package com.servlet;

import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.util.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@WebServlet("/file")
public class FileServlet extends BaseServlet {


    UserService userService = new UserServiceImpl();
    public String toFileUpload(HttpServletRequest request, HttpServletResponse response){

        //1:实现文件的存储
        //获取文件上传路劲
        String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");
        String path="";
        File saveDir = new File(uploadFilePath);
        //如果目录不存在，就创建目录
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        //封装对象
        User user = new User();
        //获取工厂文件对象
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = servletFileUpload.parseRequest(request);
            Iterator<FileItem> iterator = list.iterator();
            while (iterator.hasNext()){
                FileItem item = iterator.next();
                if(item.isFormField()){
                   String fieldName = item.getFieldName();// 获得该字段名称
                    if(fieldName.equals("uname")){
                        user.setUserName(item.getString("UTF-8"));
                    }else if(fieldName.equals("password")){
                        user.setPassword(item.getString("UTF-8"));
                    }
                }else {
                    String fileName = item.getName();// 获得文件名(全路径)
                    File file = new File(fileName);
                    String string = UUID.randomUUID().toString();
                    path=string+file.getName();
                    File file1 = new File(uploadFilePath,path);
                    item.write(file1);
                    //测试属性
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //2：实现持久话
        user.setPicPath("/upload/"+path);
        userService.addUser(user);
        return "system/file/success";

    }



    @Override
    public Class<?> getServletClass() {
        return FileServlet.class;
    }
}
